package top.fengyulou.xiaofeng.controller.web;

import com.alibaba.fastjson.support.geo.LineString;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.fengyulou.xiaofeng.common.Jr;
import top.fengyulou.xiaofeng.common.UserUtils;
import top.fengyulou.xiaofeng.common.UuidUtil;
import top.fengyulou.xiaofeng.domain.Question;
import top.fengyulou.xiaofeng.domain.UserExamPaper;
import top.fengyulou.xiaofeng.domain.UserExamQuestion;
import top.fengyulou.xiaofeng.dto.*;
import top.fengyulou.xiaofeng.enums.PaperTypeEnum;
import top.fengyulou.xiaofeng.service.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 前台用户管理
 */
@Controller
public class UserController {
    @Resource
    private PaperService paperService;
    @Resource
    private ExamService examService;
    @Resource
    private PaperQuestionRuleService paperQuestionRuleService;
    @Resource
    private QuestionService questionService;
    @Resource
    private UserExamQuestionService userExamQuestionService;
    @Resource
    private UserExamPaperService userExamPaperService;

    /**
     * 用户考试列表
     */
    @RequestMapping("/user/exam/list")
    public String userExamList(HttpSession session) {
        session.setAttribute("pageActive", "userExam");
        return "web/web-user-exam-list";
    }

    @RequestMapping("/user/exam/list/2")
    public String userExamList2(HttpSession session) {
        session.setAttribute("pageActive", "userExam");
        return "web/web-user-exam-list2";
    }

    @RequestMapping("/user/exam/child/list")
    public String userExamChildList(Model model, ExamDto examDto, HttpServletRequest request) {
        examDto.setUserId(UserUtils.getUserId(request));
        examService.getUserExamList(examDto);
        model.addAttribute("list", examDto);
        return "web/web-exam-list-child";
    }

    /**
     * 考试试卷列表
     */
    @RequestMapping("/user/paper/list/{examId}/{userExamId}")
    public String paperList(@PathVariable String examId, @PathVariable String userExamId, Model model, HttpServletRequest request) {
        ExamDto byId = examService.getById(examId);
        if (byId.getStartTime().after(new Date())) {
            model.addAttribute("msg", "考试还未开始");
            return "web/web-common-error";
        } else if (byId.getEndTime().before(new Date())) {
            model.addAttribute("msg", "考试已结束");
            return "web/web-common-error";
        }
        model.addAttribute("exam", byId);

        //查询用户考试
        ExamDto query = new ExamDto();
        query.setId(examId);
        query.setUserId(UserUtils.getUserId(request));
        ExamDto examDto = examService.webGetById(query);
        model.addAttribute("exam", examDto);

        model.addAttribute("userExamId", userExamId);

        //试卷列表
        List<PaperDto> paperDtoList = examService.getPaperListById(examId, UserUtils.getUserId(request));
        model.addAttribute("list", paperDtoList);
        return "web/web-user-paper-list";
    }

    /**
     * 考试答题页面
     */
    @RequestMapping("/user/paper/info/{examId}/{paperId}/{userExamId}")
    public String paperInfo(@PathVariable String examId, @PathVariable String paperId, @PathVariable String userExamId, Model model, HttpServletRequest request) {
        ExamDto exam = examService.getById(examId);
        if (exam.getStartTime().after(new Date())) {
            model.addAttribute("msg", "考试还未开始");
            return "web/web-common-error";
        } else if (exam.getEndTime().before(new Date())) {
            model.addAttribute("msg", "考试已结束");
            return "web/web-common-error";
        }

        model.addAttribute("examId", examId);
        model.addAttribute("userExamId", userExamId);
        //查询试卷
        PaperDto byId = paperService.getById(paperId);
        model.addAttribute("paper", byId);

        //添加试卷记录
        UserExamPaper userExamPaper = new UserExamPaper();
        userExamPaper.setExamId(examId);
        userExamPaper.setPaperId(paperId);
        userExamPaper.setUserId(UserUtils.getUserId(request));
        userExamPaper.setUserExamId(userExamId);
        userExamPaper.setTime((byId.getTime().longValue() * 60 * 1000));
        userExamPaper.setStartTime(new Date().getTime());
        UserExamPaper userExamPaper1 = examService.addUserExamPaper(userExamPaper);
        long useTime = new Date().getTime() - userExamPaper1.getStartTime();
        long surplusTime = 0;
        if (useTime < userExamPaper1.getTime()) {
            surplusTime = userExamPaper1.getTime() - useTime;
        }
        model.addAttribute("surplusTime", surplusTime);
        model.addAttribute("userExamPaper", userExamPaper1);

        //查询试题
        if (byId.getType() == PaperTypeEnum.SUIJICHUTI.getCode()) {
            List<QuestionDto> questionDtoList = new ArrayList<>();
            UserExamQuestionDto userExamQuestionDto = new UserExamQuestionDto();
            userExamQuestionDto.setUserPaperId(userExamPaper1.getId());
            List<QuestionDto> questionDtoList1Db = userExamQuestionService.list(userExamQuestionDto);
            if (ObjectUtils.isNotEmpty(questionDtoList1Db)) {
                questionDtoList.addAll(questionDtoList1Db);
            } else {
                PaperQuestionRuleDto paperQuestionRuleDto = new PaperQuestionRuleDto();
                paperQuestionRuleDto.setPaperId(paperId);
                List<PaperQuestionRuleDto> ruleList = paperQuestionRuleService.list(paperQuestionRuleDto);
                int totalQstNum = 0;
                if (ObjectUtils.isNotEmpty(ruleList)) {
                    for (PaperQuestionRuleDto questionRuleDto : ruleList) {
                        Integer qstNum = questionRuleDto.getQstNum();
                        totalQstNum = totalQstNum + qstNum;
                        //分类
                        if (questionRuleDto.getType() == 0) {
                            if (ObjectUtils.isNotEmpty(questionDtoList1Db)) {
                                questionDtoList.addAll(questionDtoList1Db);
                            } else {
                                String classifyId = questionRuleDto.getClassifyId();
                                List<QuestionDto> questionDtoList1 = questionService.getQuestionByClassifyId(classifyId, qstNum, questionRuleDto.getQstType());
                                if (ObjectUtils.isNotEmpty(questionDtoList1)) {
                                    questionDtoList.addAll(questionDtoList1);
                                }
                            }
                        }
                        //标签
                        else {
                            String labelId = questionRuleDto.getLabelId();
                            List<QuestionDto> questionDtoList1 = questionService.getQuestionByLabelId(labelId, qstNum);
                            if (ObjectUtils.isNotEmpty(questionDtoList1)) {
                                questionDtoList.addAll(questionDtoList1);
                            }
                        }
                    }
                    String userId = UserUtils.getUserId(request);
                    if (ObjectUtils.isNotEmpty(questionDtoList)) {
                        List<UserExamQuestionDto> userExamQuestionDtoList = new ArrayList<>();
                        for (int i = 0; i < questionDtoList.size(); i++) {
                            questionDtoList.get(i).setUserQstId(UuidUtil.getShortUuid());
                            QuestionDto questionDto = questionDtoList.get(i);
                            UserExamQuestionDto userQst = new UserExamQuestionDto();
                            userQst.setId(questionDto.getUserQstId());
                            userQst.setExamId(examId);
                            userQst.setPaperId(paperId);
                            userQst.setQuestionId(questionDto.getId());
                            userQst.setUserId(userId);
                            userQst.setUserPaperId(userExamPaper1.getId());
                            userQst.setUserExamId(userExamId);
                            userQst.setCreateTime(new Date());
                            userQst.setSort(i);
                            userExamQuestionDtoList.add(userQst);
                        }
                        if (totalQstNum == userExamQuestionDtoList.size()) {
                            userExamQuestionService.insertBatch(userExamQuestionDtoList);
                        } else {
                            questionDtoList = null;
                        }
                    }
                }
            }
            model.addAttribute("list", questionDtoList);
        } else {
            List<QuestionDto> questionDtoList = new ArrayList<>();
            UserExamQuestionDto userExamQuestionDto = new UserExamQuestionDto();
            userExamQuestionDto.setUserPaperId(userExamPaper1.getId());
            List<QuestionDto> questionDtoList1Db = userExamQuestionService.list(userExamQuestionDto);
            if (ObjectUtils.isNotEmpty(questionDtoList1Db)) {
                questionDtoList.addAll(questionDtoList1Db);
            } else {
                List<QuestionDto> qstListByPaperId = paperService.getQstListByPaperId(paperId);
                questionDtoList.addAll(qstListByPaperId);
                if (ObjectUtils.isNotEmpty(qstListByPaperId)) {
                    List<UserExamQuestionDto> userExamQuestionDtoList = new ArrayList<>();
                    for (int i = 0; i < qstListByPaperId.size(); i++) {
                        qstListByPaperId.get(i).setUserQstId(UuidUtil.getShortUuid());
                        QuestionDto questionDto = qstListByPaperId.get(i);
                        UserExamQuestionDto userQst = new UserExamQuestionDto();
                        userQst.setId(questionDto.getUserQstId());
                        userQst.setExamId(examId);
                        userQst.setPaperId(paperId);
                        userQst.setQuestionId(questionDto.getId());
                        userQst.setUserId(UserUtils.getUserId(request));
                        userQst.setUserPaperId(userExamPaper1.getId());
                        userQst.setUserExamId(userExamId);
                        userQst.setCreateTime(new Date());
                        userQst.setSort(i);
                        userExamQuestionDtoList.add(userQst);
                    }
                    userExamQuestionService.insertBatch(userExamQuestionDtoList);
                }
            }
            model.addAttribute("list", questionDtoList);
        }
        return "web/web-user-paper-info";
    }

    /**
     * 考试解析页面
     */
    @RequestMapping("/user/paper/parse/{examId}/{paperId}/{userExamId}/{userPaperId}")
    public String paperParse(@PathVariable String examId, @PathVariable String paperId, @PathVariable String userExamId, @PathVariable String userPaperId, Model model, HttpServletRequest request) {
        model.addAttribute("examId", examId);
        model.addAttribute("userExamId", userExamId);
        //查询试卷
        PaperDto byId = paperService.getById(paperId);
        model.addAttribute("paper", byId);

        //试卷记录
        UserExamPaperDto userExamPaperDto = userExamPaperService.getById(userPaperId);
        model.addAttribute("userPaper", userExamPaperDto);

        //查询试卷记录信息
        UserExamQuestionDto userExamQuestionDto = new UserExamQuestionDto();
        userExamQuestionDto.setUserPaperId(userPaperId);
        userExamQuestionDto.setUserId(UserUtils.getUserId(request));
        List<QuestionDto> questionDtoList = userExamQuestionService.parseList(userExamQuestionDto);
        model.addAttribute("questionList", questionDtoList);
        return "web/web-user-paper-parse";
    }

    /**
     * 用户信息详情
     */
    @RequestMapping("/user/info")
    public String info() {
        return "web/web-user-info";
    }

    //提交试题
    @RequestMapping("/user/ajax/submit/qst")
    @ResponseBody
    public Jr submitQst(@RequestParam String paperId, @RequestParam String qstId, @RequestParam String userQuestionId, @RequestParam String userAnswer, HttpServletRequest request) {
        UserExamQuestion userExamQuestion = new UserExamQuestion();
        userExamQuestion.setId(userQuestionId);
        userExamQuestion.setQuestionId(qstId);
        userExamQuestion.setPaperId(paperId);
        userExamQuestion.setUserId(UserUtils.getUserId(request));
        userExamQuestion.setUserAnswer(userAnswer);
        userExamQuestion.setCurrentUserId(UserUtils.getUserId(request));
        examService.addUserExamQuestion(userExamQuestion);
        return Jr.yes();
    }

    //提交试卷
    @RequestMapping("/user/ajax/submit/paper")
    @ResponseBody
    public Jr submitPaper(@RequestParam String userPaperId, HttpServletRequest request) {
        UserExamPaper userExamPaper = new UserExamPaper();
        userExamPaper.setId(userPaperId);
        userExamPaper.setUserId(UserUtils.getUserId(request));
        userExamPaper.setCurrentUserId(UserUtils.getUserId(request));
        examService.updateExamPaperStatus(userExamPaper);
        return Jr.yes();
    }
}
